<template>
    <div class="list-wrapper">
        <Block>
            <DataGrid :auto-load="autoLoad" ref="dataGridRef">
                <template #toolbar-search>
                    <div class="query-from-box">
                        <el-form>
                            <el-form-item>
                                <el-input v-model="queryData.protocolKey" placeholder="协议名称/标识符" clearable />
                            </el-form-item>
                            <el-form-item>
                                <el-select placeholder="协议类型" v-model="queryData.protocolType" clearable>
                                    <el-option
                                        v-for="(item, i) in protocolTypeList"
                                        :label="item.protocolType"
                                        :key="i"
                                        :value="item.protocolType"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                </template>
                <template #toolbar-operation>
                    <el-button type="primary" @click="onCreateEdit()">新建</el-button>
                    <el-upload :http-request="onImport" :show-file-list="false" style="display: flex; margin: 0 10px">
                        <el-button type="primary" plain>导入</el-button>
                    </el-upload>
                </template>
                <el-table-column type="index" label="序号" width="60" align="center" fixed />
                <el-table-column label="协议名称" width="300" fixed show-overflow-tooltip>
                    <template #default="scope">
                        <el-button link type="primary" @click="onGoDetail(scope.row)">
                            {{ scope.row.protocolName }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="protocolNo" label="标识符" show-overflow-tooltip />
                <el-table-column prop="protocolType" label="协议类型" show-overflow-tooltip>
                    <template #default="scope">
                        <div class="table-item-tag">
                            <el-tag
                                :type="
                                    scope.row.protocolType === 'modbus'
                                        ? 'warning'
                                        : scope.row.protocolType === 'mqtt'
                                          ? 'primary'
                                          : 'success'
                                "
                            >
                                {{ scope.row.protocolType }}
                            </el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="protocolDescription" label="描述" show-overflow-tooltip />
                <el-table-column label="操作" width="150" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" @click="onCreateEdit(scope.row)"> 修改 </el-button>
                        <el-button link type="danger" @click="onDel(scope.row)"> 删除 </el-button>
                        <el-button
                            link
                            type="primary"
                            @click="onExport(scope.row)"
                            :loading="loading && loading[scope.row.protocolNo]"
                        >
                            导出
                        </el-button>
                    </template>
                </el-table-column>
            </DataGrid>
        </Block>
    </div>
</template>
<script setup lang="ts">
import { IoTProtocolService } from '@great/services';
import { useRouter } from 'vue-router';
import { checkPermi } from '@/utils/ruoyi';
import { showPopupBox } from '@great/utils';
import CreateEditModal from './components/list/CreateEditModal.vue';
import { DataGrid, Block, type DataGridInstance } from '@great/components';
import type { UploadRequestHandler, UploadRequestOptions } from 'element-plus';

const router = useRouter();
// 查询条件
const queryData = ref({
    protocolType: '',
    protocolKey: ''
});
const loading = ref({});
const dataGridRef = useTemplateRef<DataGridInstance>('dataGridRef');
const autoLoad = reactive({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async (current, size) => {
        const res = await IoTProtocolService.getProtocolPublicPage({
            current,
            size,
            ...queryData.value
        });
        loading.value = {};
        return { data: res.data.records, total: res.data.total };
    }
});
const protocolTypeList = ref<
    Array<{
        id: string;
        protocolType: string;
        userDefined: boolean;
    }>
>([]);
// 查看详情
const onGoDetail = (row: { id: string }) => {
    if (checkPermi(['iot:protocol:detail'])) {
        router.push({
            name: 'IoT-protocol-detail',
            params: {
                id: row?.id
            }
        });
    }
};
// 创建/编辑
const onCreateEdit = (row?: any) => {
    showPopupBox(CreateEditModal, {
        row: row,
        callBack: dataGridRef.value?.refresh
    });
};
// 删除
const onDel = async (row: { protocolName: string; protocolNo: string }) => {
    const res: any = await IoTProtocolService.verifyDelProtocol(row.protocolNo);
    if (res.data) {
        ElNotification({
            title: '删除失败！',
            message: res.msg,
            type: 'error'
        });
    } else {
        ElMessageBox.confirm(`确认删除协议 ${row.protocolName} ？`, '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(async () => {
                await IoTProtocolService.delProtocol(row.protocolNo);
                ElNotification({
                    title: '删除成功！',
                    type: 'success'
                });
                dataGridRef.value?.refresh();
            })
            .catch(() => {});
    }
};
// 转formData
const toFormData = (schemaObj, fileObj): FormData => {
    const formData = new FormData();
    // 将 schemaObj 的所有属性添加到 formData
    if (schemaObj && typeof schemaObj === 'object') {
        Object.keys(schemaObj).forEach(key => {
            const value = schemaObj[key];
            if (typeof value === 'object' && value !== null) {
                if (Array.isArray(value)) {
                    value.forEach((item, index) => {
                        formData.append(`${key}[${index}]`, item);
                    });
                } else {
                    formData.append(key, JSON.stringify(value));
                }
            } else {
                formData.append(key, value);
            }
        });
    }
    // 处理文件对象
    if (fileObj) {
        if (Array.isArray(fileObj)) {
            if (fileObj.length === 1) {
                formData.append('file', fileObj[0]);
            } else {
                fileObj.forEach((file, index) => {
                    formData.append(`file${index}`, file);
                });
            }
        } else {
            formData.append('file', fileObj);
        }
    }
    return formData;
};

// 导入
const onImport: UploadRequestHandler = async (opt: UploadRequestOptions) => {
    let formData = toFormData(null, opt.file);
    await IoTProtocolService.importProtocol(formData);
    ElNotification({
        title: '导入成功！',
        type: 'success'
    });
};
// 导出
const onExport = async (row: { protocolNo: string }) => {
    loading.value[row.protocolNo] = true;
    await IoTProtocolService.exportProtocol(row.protocolNo);
    loading.value[row.protocolNo] = false;
};
// 获取协议类型列表
const getProtocolTypeList = async () => {
    const res = await IoTProtocolService.getProtocolTypeList();
    protocolTypeList.value = res.data;
};
getProtocolTypeList();
</script>

<style scoped lang="scss">
.list-wrapper {
    .query-from-box {
        display: flex;
        align-items: center;
        .el-form {
            display: flex;
            .el-form-item {
                margin-bottom: 0;
                width: 192px;
            }
            .el-form-item + .el-form-item {
                margin-left: 10px;
            }
        }
    }
    :deep(.data-grid) {
        .table-item-tag {
            display: flex;
        }
    }
}
</style>
